#!/bin/bash

# 单脚本 Docker 化安装 Nacos (使用现有 MySQL)
# 执行要求：以 root 用户或具有 sudo 权限的用户运行

# 用户配置区 ===================================================
MYSQL_HOST="14.44.128.120"           # MySQL 主机地址
MYSQL_PORT="18306"                   # MySQL 端口
MYSQL_ROOT_PWD="Test@123"            # MySQL root 密码
MYSQL_NACOS_USER="nacos"             # Nacos 数据库用户名
MYSQL_NACOS_PWD="nacos"              # Nacos 数据库密码
NACOS_VERSION="2.3.1"                # Nacos 版本
NACOS_HOST_PORT="8848"               # 宿主机映射端口
# =============================================================

# 依赖检查函数
check_dependencies() {
    local missing=()

    # 检查 Docker
    if ! command -v docker &>/dev/null; then
        missing+=("Docker")
        echo "错误: Docker 未安装，正在尝试自动安装..."
        curl -fsSL https://get.docker.com | sh || {
            echo "Docker 自动安装失败，请手动安装后重试！"
            exit 1
        }
        systemctl enable --now docker
    fi

    # 检查 docker-compose
    if ! command -v docker-compose &>/dev/null; then
        missing+=("Docker Compose")
        echo "安装 Docker Compose..."
        sudo curl -L "https://github.com/docker/compose/releases/download/v2.23.0/docker-compose-$(uname -s)-$(uname -m)" \
            -o /usr/local/bin/docker-compose
        sudo chmod +x /usr/local/bin/docker-compose
    fi

    # 检查 MySQL 客户端
    if ! command -v mysql &>/dev/null; then
        missing+=("MySQL Client")
        echo "安装 MySQL 客户端..."
        if [[ -f /etc/redhat-release ]]; then
            yum install -y mysql
        else
            apt-get update && apt-get install -y mysql-client
        fi
    fi

    # 如果有缺失组件且自动安装失败
    if [[ ${#missing[@]} -gt 0 ]]; then
        echo "以下依赖未安装: ${missing[*]}"
        exit 1
    fi
}

# 数据库初始化函数
init_database() {
    echo "正在初始化 Nacos 数据库..."

    # 检查 MySQL 连接
    if ! mysql -u root -p"${MYSQL_ROOT_PWD}" -h "${MYSQL_HOST}" -P "${MYSQL_PORT}" -e "SELECT 1" &>/dev/null; then
        echo "MySQL 连接失败！请检查："
        echo "1. 确保 MySQL 已运行且端口开放"
        echo "2. 检查 root 密码是否正确"
        echo "3. 确认用户 root 允许远程连接"
        exit 1
    fi

    # 执行数据库操作
    mysql -u root -p"${MYSQL_ROOT_PWD}" -h "${MYSQL_HOST}" -P "${MYSQL_PORT}" <<SQL
CREATE DATABASE IF NOT EXISTS nacos CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${MYSQL_NACOS_USER}'@'%' IDENTIFIED BY '${MYSQL_NACOS_PWD}';
GRANT ALL PRIVILEGES ON nacos.* TO '${MYSQL_NACOS_USER}'@'%';
FLUSH PRIVILEGES;
SQL

    # 下载并导入 SQL 结构
    NACOS_SQL_URL="https://raw.githubusercontent.com/alibaba/nacos/${NACOS_VERSION}/distribution/conf/mysql-schema.sql"
    if ! curl -fsSL "${NACOS_SQL_URL}" | mysql -u root -p"${MYSQL_ROOT_PWD}" -h "${MYSQL_HOST}" -P "${MYSQL_PORT}" nacos; then
        echo "数据库初始化失败！请检查网络或手动下载 SQL 文件。"
        exit 1
    fi
}

# 生成 Docker Compose 文件
generate_compose() {
    local secret_key=$(openssl rand -base64 48 | tr -d '/+=\n' | cut -c1-64)

    cat > docker-compose.yml <<-EOF
version: '2'
services:
  nacos:
    image: nacos/nacos-server:v${NACOS_VERSION}
    container_name: nacos
    ports:
      - "${NACOS_HOST_PORT}:8848"
    environment:
      - MODE=standalone
      - SPRING_DATASOURCE_PLATFORM=mysql
      - MYSQL_SERVICE_HOST=${MYSQL_HOST}
      - MYSQL_SERVICE_PORT=${MYSQL_PORT}
      - MYSQL_SERVICE_DB_NAME=nacos
      - MYSQL_SERVICE_USER=${MYSQL_NACOS_USER}
      - MYSQL_SERVICE_PASSWORD=${MYSQL_NACOS_PWD}
      - NACOS_AUTH_ENABLE=true
      - NACOS_AUTH_TOKEN=${secret_key}
      - NACOS_AUTH_IDENTITY_KEY=security
      - NACOS_AUTH_IDENTITY_VALUE=identity
    restart: always
    extra_hosts:
      - "host.docker.internal:host-gateway"
EOF

    echo "生成 docker-compose.yml 完成！安全密钥已自动配置。"
}

# 主流程
main() {
    # 检查依赖
    check_dependencies

    # 初始化数据库
    init_database

    # 生成 Docker Compose 文件
    generate_compose

    # 启动服务
    echo "启动 Nacos 容器..."
    docker-compose up -d

    # 验证部署
    sleep 10
    if docker ps | grep -q nacos; then
        echo "部署成功！"
        echo "访问地址: http://$(curl -s ifconfig.me):${NACOS_HOST_PORT}/nacos"
        echo "用户名: nacos"
        echo "密码: nacos"
        echo "安全密钥: $(grep NACOS_AUTH_TOKEN docker-compose.yml | cut -d= -f2)"
    else
        echo "启动失败，请检查日志: docker logs nacos"
        exit 1
    fi
}

# 执行主函数
main